import { maleArr, femaleArr, criticalValueArr, k1k2 } from "./mean";

function getage(birthDate, creatDate) {
  // 1. 统一替换 '-' 为 '/'（增强兼容性）
  const normalizeDate = (dateStr) => dateStr.replace(/-/g, "/");

  // 2. 解析日期（兼容小程序和浏览器）
  const parseDate = (dateStr) => {
    const date = new Date(normalizeDate(dateStr));
    if (isNaN(date.getTime())) {
      throw new Error(`Invalid date: ${dateStr}`);
    }
    return date;
  };

  // 3. 解析 birthDate 和 creatDate
  const birth = parseDate(birthDate);
  const creat = parseDate(creatDate);

  // 4. 计算年份差
  let age = creat.getFullYear() - birth.getFullYear();

  // 5. 检查是否已过生日（精确到月份和日期）
  const creatMonth = creat.getMonth();
  const birthMonth = birth.getMonth();
  const creatDay = creat.getDate();
  const birthDay = birth.getDate();

  if (
    creatMonth < birthMonth ||
    (creatMonth === birthMonth && creatDay < birthDay)
  ) {
    age--; // 如果 creatDate 时还未过生日，年龄减1
  }

  return age;
}
export function formatData(recordsData, userData) {
  // 先根据 selfMag.createDate 进行倒序排序
  const sortedData = [...recordsData].sort((a, b) => {
    // 1. 统一日期格式（将 "2025-6-12" 转为 "2025/6/12"）
    const formatDate = (dateStr) => dateStr?.replace(/-/g, "/") || "";

    // 2. 解析日期（兼容小程序和iOS）
    const dateA = new Date(formatDate(a.selfMag?.createDate));
    const dateB = new Date(formatDate(b.selfMag?.createDate));

    // 3. 如果日期相同，则使用createTime进行排序
    if (dateA.getTime() === dateB.getTime()) {
      return (b.createTime || 0) - (a.createTime || 0);
    }

    // 4. 倒序排序（最新的在前）
    return dateB - dateA;
  });

  // 提取并去重医院标签
  const hospitalSet = new Set(["所有"]);
  sortedData.forEach((item) => {
    if (item.selfMag && item.selfMag.hospital) {
      hospitalSet.add(item.selfMag.hospital);
    }
  });

  const birthDate =
    typeof userData === "object" && userData !== null
      ? userData.birthDate
      : userData;

  // 然后处理每条记录的数据
  sortedData.forEach((item, index) => {
    item.changRadio = false;
    item.selfMag.age = getage(birthDate, item.selfMag.createDate);
    // 新增：根据性别和年龄赋值均值
    let meanValue = null;
    if (userData && userData.sexRadio && item.selfMag.age) {
      const arr = userData.sexRadio === "男" ? maleArr : femaleArr;
      let targetAge =
        Number(item.selfMag.age) >= 18 ? "18" : String(item.selfMag.age);
      const found = arr.find((v) => String(v.age) === targetAge);
      meanValue = found ? found.value : null;
    }
    item.meanValue = meanValue;
    item.ygd.lyleftStr = item.ygd.lyleft.split("/")[0];
    item.ygd.lyrightStr = item.ygd.lyright.split("/")[0];
    item.ygd.jzrightStr = item.ygd.jzright.split("/")[0];
    item.ygd.jzleftStr = item.ygd.jzleft.split("/")[0];
    item.ygd.jsright =
      Math.round(item.yzd.K2R2right - item.yzd.K1R1right) * 100;
    item.ygd.jsleft = Math.round(item.yzd.K2R2left - item.yzd.K1R1left) * 100;
    // 新增：根据年龄和k1左右赋值临界值
    item.ygd = item.ygd || {};
    item.ygd.criticalright = getCriticalValue(
      item.yzd.K1R1right,
      item.selfMag.age
    );
    item.ygd.criticalleft = getCriticalValue(
      item.yzd.K1R1left,
      item.selfMag.age
    );
    // 新增：计算轴余
    item.ygd.axisSurplusright =
      item.ygd.criticalright && item.yzd.ALright
        ? (Number(item.ygd.criticalright) - Number(item.yzd.ALright)).toFixed(2)
        : null;
    item.ygd.axisSurplusleft =
      item.ygd.criticalleft && item.yzd.ALleft
        ? (Number(item.ygd.criticalleft) - Number(item.yzd.ALleft)).toFixed(2)
        : null;
    console.log(item.selfMag.age);
  });

  return {
    sortedData,
    hospitalTag: Array.from(hospitalSet),
  };
}
function calculateTimeDiff(date1, date2) {
  // 修复1：统一日期格式（将 "2025-6-12" 转为 "2025/6/12"）
  const parseDate = (dateStr) => {
    return new Date(
      typeof dateStr === "string" ? dateStr.replace(/-/g, "/") : dateStr
    );
  };
  const d1 = parseDate(date1);
  const d2 = parseDate(date2);
  // 修复2：计算绝对时间差（毫秒），避免跨月问题
  const timeDiff = Math.abs(d1 - d2); // 毫秒差
  const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24)); // 总天数差
  // 转换为月份和天数
  const months = Math.floor(daysDiff / 30); // 近似月份（按30天算）
  const days = daysDiff % 30; // 剩余天数
  // 格式化输出
  let timeStr = "";
  if (months > 0) timeStr += `${months}个月`;
  if (days > 0) timeStr += `${days}天`;
  if (timeStr === "") timeStr = "0天";
  return timeStr;
}
export function handleTags(sortedData) {
  sortedData.forEach((item, index) => {
    item.tipsGreen = [item.tagSelect.insetTime, item.tagSelect.glassyes].concat(
      item.tagSelect.superimpose
    );
    item.tipsRed = [item.tagSelect.allergy, item.tagSelect.useDateTime]
      .concat(item.tagSelect.glass)
      .concat(item.tagSelect.sitdown);

    // 计算小瞳度数差值
    if (index < sortedData.length - 1) {
      const prevItem = sortedData[index + 1];
      item.hitomiDiff = {
        right: Math.ceil(
          item.ygd.hitomiright * 100 - prevItem.ygd.hitomiright * 100
        ),
        left: Math.ceil(
          item.ygd.hitomileft * 100 - prevItem.ygd.hitomileft * 100
        ),
        ALright: (item.yzd.ALright - prevItem.yzd.ALright).toFixed(2),
        ALleft: (item.yzd.ALleft - prevItem.yzd.ALleft).toFixed(2),
        isFirst: false,
        timeDiff: calculateTimeDiff(
          item.selfMag.createDate,
          prevItem.selfMag.createDate
        ),
        speedRight: (() => {
          const timeDiff = calculateTimeDiff(
            item.selfMag.createDate,
            prevItem.selfMag.createDate
          );
          const months = parseInt(timeDiff.split("个月")[0]) || 0;
          const days = parseInt(timeDiff.split("天")[0]) || 0;
          const totalDays = months * 30 + days;
          if (totalDays <= 0) return 0;
          const diff = (item.ygd.hitomiright - prevItem.ygd.hitomiright) * 100;
          // 计算年增长率：(差值/天数) * 365
          return Math.round((diff / totalDays) * 365);
        })(),
        speedLeft: (() => {
          const timeDiff = calculateTimeDiff(
            item.selfMag.createDate,
            prevItem.selfMag.createDate
          );
          const months = parseInt(timeDiff.split("个月")[0]) || 0;
          const days = parseInt(timeDiff.split("天")[0]) || 0;
          const totalDays = months * 30 + days;
          if (totalDays <= 0) return 0;
          const diff = (item.ygd.hitomileft - prevItem.ygd.hitomileft) * 100;
          // 计算年增长率：(差值/天数) * 365
          return Math.round((diff / totalDays) * 365);
        })(),
        speedALright: (() => {
          const timeDiff = calculateTimeDiff(
            item.selfMag.createDate,
            prevItem.selfMag.createDate
          );
          const months = parseInt(timeDiff.split("个月")[0]) || 0;
          const days = parseInt(timeDiff.split("天")[0]) || 0;
          const totalDays = months * 30 + days;
          if (totalDays <= 0) return 0;
          const diff = item.yzd.ALright - prevItem.yzd.ALright;
          // 计算年增长率：(差值/天数) * 365
          return ((diff / totalDays) * 365).toFixed(2);
        })(),
        speedALleft: (() => {
          const timeDiff = calculateTimeDiff(
            item.selfMag.createDate,
            prevItem.selfMag.createDate
          );
          const months = parseInt(timeDiff.split("个月")[0]) || 0;
          const days = parseInt(timeDiff.split("天")[0]) || 0;
          const totalDays = months * 30 + days;
          if (totalDays <= 0) return 0;
          const diff = item.yzd.ALleft - prevItem.yzd.ALleft;
          // 计算年增长率：(差值/天数) * 365
          return ((diff / totalDays) * 365).toFixed(2);
        })(),
      };
    } else {
      // 第一次检查的标识
      item.hitomiDiff = {
        right: 0,
        left: 0,
        ALright: 0,
        ALleft: 0,
        isFirst: true,
        timeDiff: "首次检查",
      };
    }
  });

  return sortedData;
}

function getCriticalArrByAge(age) {
  if (age >= 3 && age <= 5) return criticalValueArr.threetofive;
  if (age >= 6 && age <= 9) return criticalValueArr.sixtonine;
  if (age >= 10 && age <= 12) return criticalValueArr.tentotwelve;
  if (age >= 13 && age <= 15) return criticalValueArr.thirteentofifteen;
  if (age >= 16) return criticalValueArr.sixteentoeighteen;
  return [];
}

function getCriticalValue(k1, age) {
  const arr = getCriticalArrByAge(age);
  const idx = k1k2.indexOf(String(Number(k1).toFixed(1)));
  if (arr.length && idx !== -1) {
    return arr[idx];
  }
  return null;
}
